<template>
  <view class="container">
    <!-- 顶部标题 -->
    <view class="page-header">
      <text class="page-title">智能匹配金融产品</text>
      <text class="page-subtitle">根据您的需求，为您推荐最适合的金融产品</text>
    </view>

    <!-- 客户信息选择 -->
    <view class="selection-section">
      <view class="section-title">请选择偏好条件</view>
      <view class="section-desc">可多选，系统将智能匹配产品</view>
      
      <view class="preference-grid">
        <view 
          class="preference-item" 
          v-for="(pref, index) in preferences" 
          :key="index"
          :class="{ active: selectedPreferences.includes(pref.id) }"
          @click="togglePreference(pref.id)"
        >
          <view class="preference-icon">{{ pref.icon }}</view>
          <text class="preference-name">{{ pref.name }}</text>
          <text class="preference-desc">{{ pref.desc }}</text>
        </view>
      </view>
    </view>

    <!-- 匹配结果 -->
    <view class="results-section" v-if="matchedProducts.length > 0">
      <view class="section-header">
        <text class="section-title">为您匹配到 {{ matchedProducts.length }} 个产品</text>
        <view class="match-score" v-if="bestMatchProduct">
          <text class="match-text">匹配度</text>
          <text class="match-value">{{ bestMatchProduct.matchRate }}%</text>
        </view>
      </view>
      
      <!-- 最佳匹配产品 -->
      <view class="best-match" v-if="bestMatchProduct">
        <view class="best-match-tag">最佳匹配</view>
        <view class="product-card featured">
          <view class="product-header">
            <view class="product-badge" :style="{ backgroundColor: bestMatchProduct.badgeColor }">
              {{ bestMatchProduct.badge }}
            </view>
            <image class="product-logo" :src="bestMatchProduct.logo" mode="aspectFit"></image>
            <view class="product-info">
              <text class="product-name">{{ bestMatchProduct.name }}</text>
              <text class="product-company">{{ bestMatchProduct.company }}</text>
            </view>
          </view>
          
          <view class="product-features">
            <view class="feature-tag" v-for="(feature, idx) in bestMatchProduct.features" :key="idx">
              {{ feature }}
            </view>
          </view>
          
          <view class="product-details">
            <view class="detail-item">
              <text class="detail-label">额度范围</text>
              <text class="detail-value">{{ bestMatchProduct.quota }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">年化利率</text>
              <text class="detail-value">{{ bestMatchProduct.rate }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">放款速度</text>
              <text class="detail-value">{{ bestMatchProduct.speed }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">申请条件</text>
              <text class="detail-value">{{ bestMatchProduct.condition }}</text>
            </view>
          </view>
          
          <view class="product-match-reasons">
            <text class="match-reason-title">匹配理由：</text>
            <view class="match-reasons">
              <text class="match-reason" v-for="(reason, idx) in bestMatchProduct.matchReasons" :key="idx">
                {{ reason }}
              </text>
            </view>
          </view>
          
          <view class="product-actions">
            <button class="detail-btn" @click="viewProductDetail(bestMatchProduct.id)">查看详情</button>
            <button class="apply-btn" @click="bindProduct(bestMatchProduct.id)">完成匹配</button>
          </view>
        </view>
      </view>
      
      <!-- 其他匹配产品 -->
      <view class="other-products" v-if="matchedProducts.length > 1">
        <view class="section-title">其他推荐产品</view>
        <view class="product-list">
          <view 
            class="product-card" 
            v-for="product in otherProducts" 
            :key="product.id"
          >
            <view class="product-header">
              <view class="product-badge" :style="{ backgroundColor: product.badgeColor }">
                {{ product.badge }}
              </view>
              <image class="product-logo" :src="product.logo" mode="aspectFit"></image>
              <view class="product-info">
                <text class="product-name">{{ product.name }}</text>
                <text class="product-company">{{ product.company }}</text>
              </view>
              <view class="match-rate">{{ product.matchRate }}%</view>
            </view>
            
            <view class="product-features">
              <view class="feature-tag" v-for="(feature, idx) in product.features" :key="idx">
                {{ feature }}
              </view>
            </view>
            
            <view class="product-summary">
              <view class="summary-item">
                <text class="summary-label">额度</text>
                <text class="summary-value">{{ product.quota }}</text>
              </view>
              <view class="summary-item">
                <text class="summary-label">利率</text>
                <text class="summary-value">{{ product.rate }}</text>
              </view>
              <view class="summary-item">
                <text class="summary-label">放款</text>
                <text class="summary-value">{{ product.speed }}</text>
              </view>
            </view>
            
            <view class="product-actions">
              <button class="detail-btn" @click="viewProductDetail(product.id)">查看详情</button>
              <!-- <button class="apply-btn" @click="applyProduct(product.id)">申请</button> -->
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 无匹配结果 -->
    <view class="empty-state" v-else-if="hasSearched">
      <image class="empty-icon" src="/static/images/no-match.png"></image>
      <text class="empty-title">暂无匹配产品</text>
      <text class="empty-desc">抱歉，根据您选择的条件没有找到完全匹配的产品</text>
      <view class="empty-actions">
        <button class="reset-btn" @click="resetSelection">重新选择条件</button>
        <!-- <button class="contact-btn" @click="contactAdvisor">联系顾问</button> -->
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="action-bar">
      <button class="match-btn" @click="matchProducts" :disabled="selectedPreferences.length === 0">
        <text class="btn-text">开始匹配</text>
        <text class="btn-count" v-if="selectedPreferences.length > 0">
          {{ selectedPreferences.length }}个条件
        </text>
      </button>
    </view>
  </view>
</template>

<script>
    const productOBJ=uniCloud.importObject('mydb-product')
export default {
  data() {
    return {
      selectedPreferences: [],
      hasSearched: false,
      preferences: [],
      allProducts: [],
      matchedProducts: []
    }
  },
  computed: {
    bestMatchProduct() {
      if (this.matchedProducts.length === 0) return null
      return this.matchedProducts[0]
    },
    otherProducts() {
      if (this.matchedProducts.length <= 1) return []
      return this.matchedProducts.slice(1)
    }
  },
  onLoad(option) {
    if (option.customerId) {
      productOBJ.getOptions(option.customerId).then((res) => {
        if (res.data) {
          this.preferences = res.data.preferences || []
          this.allProducts = res.data.allProducts || []
        }
      })
    }else{
        uni.showToast({
          title: '请先选择客户',
          icon: 'none'
        })
    }
  },
  methods: {
    togglePreference(prefId) {
      const index = this.selectedPreferences.indexOf(prefId)
      if (index > -1) {
        this.selectedPreferences.splice(index, 1)
      } else {
        this.selectedPreferences.push(prefId)
      }
    },
    matchProducts() {
      if (this.selectedPreferences.length === 0) {
        uni.showToast({
          title: '请至少选择一个条件',
          icon: 'none'
        })
        return
      }
      
      // 模拟匹配算法
      // 实际项目中这里应该是调用后端API进行智能匹配
      this.hasSearched = true
      
      // 根据用户选择的偏好条件计算产品匹配度
      const scoredProducts = this.allProducts.map(product => {
        let score = 0
        let matchedReasons = []
        
        // 计算匹配分数
        this.selectedPreferences.forEach(prefId => {
          const prefName = this.getPreferenceName(prefId)
          if (product.features.includes(prefName)) {
            score += 20 // 每个匹配条件加20分
            matchedReasons.push(`符合您的${prefName}要求`)
          }
        })
        
        // 添加额外匹配理由
        if (matchedReasons.length === 0) {
          // 如果没有直接匹配，尝试找相关匹配
          this.selectedPreferences.forEach(prefId => {
            const relatedReasons = this.getRelatedReasons(prefId, product)
            if (relatedReasons) {
              matchedReasons.push(relatedReasons)
              score += 10 // 相关匹配加10分
            }
          })
        }
        
        // 确保匹配理由不超过3条
        if (matchedReasons.length > 3) {
          matchedReasons = matchedReasons.slice(0, 3)
        }
        
        return {
          ...product,
          matchRate: Math.min(score, 100),
          matchReasons: matchedReasons.length > 0 ? matchedReasons : ['产品符合部分您的需求']
        }
      })
      
      // 按匹配度排序
      this.matchedProducts = scoredProducts
        .filter(product => product.matchRate >= 50) // 只显示匹配度50%以上的产品
        .sort((a, b) => b.matchRate - a.matchRate)
      
      // 滚动到结果区域
      setTimeout(() => {
        const query = uni.createSelectorQuery()
        query.select('.results-section').boundingClientRect()
        query.exec(res => {
          if (res[0]) {
            uni.pageScrollTo({
              scrollTop: res[0].top - 80,
              duration: 300
            })
          }
        })
      }, 100)
    },
    getPreferenceName(prefId) {
      const pref = this.preferences.find(p => p.id === prefId)
      return pref ? pref.name : ''
    },
    getRelatedReasons(prefId, product) {
      // 根据偏好条件和产品特性生成相关匹配理由
      const reasons = {
        low_threshold: product.condition.includes('宽松') || product.condition.includes('简单') ? 
          '申请条件相对宽松' : null,
        low_rate: parseFloat(product.rate) < 5 ? '利率水平较低' : null,
        high_quota: product.quota.includes('50') || product.quota.includes('100') ? 
          '授信额度较高' : null,
        fast_loan: product.speed.includes('分钟') || product.speed.includes('小时') || 
          product.speed.includes('当天') ? '放款速度较快' : null,
        long_term: product.features.includes('期限长') ? '贷款期限较长' : null,
        flexible_repayment: product.features.includes('还款灵活') ? '还款方式灵活' : null,
        no_collateral: product.features.includes('免抵押') ? '无需抵押担保' : null,
        online_process: product.features.includes('全线上') ? '支持线上办理' : null
      }
      
      return reasons[prefId] || null
    },
    viewProductDetail(productId) {
      uni.navigateTo({
        url: `/pages/product/detail?productId=${productId}`
      })
    },
    applyProduct(productId) {
      uni.showModal({
        title: '确认申请',
        content: '确定要申请该金融产品吗？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: `/pages/contact/contact?id=${productId}`
            })
          }
        }
      })
    },
    bindProduct(productId) {
      uni.showModal({
        title: '确认绑定',
        content: '确定要绑定该金融产品吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '绑定成功',
              icon: 'success'
            })
          }
        }
      })
    },
    resetSelection() {
      this.selectedPreferences = []
      this.matchedProducts = []
      this.hasSearched = false
    },
    contactAdvisor() {
      uni.makePhoneCall({
        phoneNumber: '400-888-9999'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  padding-bottom: 140rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 40rpx;
  
  .page-title {
    display: block;
    font-size: 40rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .page-subtitle {
    display: block;
    font-size: 26rpx;
    color: #666;
  }
}

.selection-section {
  background: white;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 12rpx;
  }
  
  .section-desc {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 40rpx;
  }
  
  .preference-grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    
    .preference-item {
      width: 48%;
      background: #f8fafc;
      border: 2rpx solid #f0f0f0;
      border-radius: 16rpx;
      padding: 30rpx 20rpx;
      margin-bottom: 20rpx;
      text-align: center;
      transition: all 0.3s;
      box-sizing: border-box;
      &.active {
        border-color: #4a90e2;
        background: #e6f3ff;
        box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.2);
        
        .preference-icon {
          transform: scale(1.1);
        }
        
        .preference-name {
          color: #4a90e2;
        }
      }
      
      .preference-icon {
        font-size: 60rpx;
        margin-bottom: 16rpx;
        transition: all 0.3s;
      }
      
      .preference-name {
        display: block;
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .preference-desc {
        display: block;
        font-size: 22rpx;
        color: #999;
      }
    }
  }
}

.results-section {
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .match-score {
      display: flex;
      align-items: center;
      background: #f6ffed;
      border: 1rpx solid #b7eb8f;
      border-radius: 20rpx;
      padding: 8rpx 16rpx;
      
      .match-text {
        font-size: 22rpx;
        color: #52c41a;
        margin-right: 8rpx;
      }
      
      .match-value {
        font-size: 24rpx;
        font-weight: bold;
        color: #52c41a;
      }
    }
  }
}

.best-match {
  position: relative;
  margin-bottom: 40rpx;
  
  .best-match-tag {
    position: absolute;
    top: -10rpx;
    left: 30rpx;
    background: linear-gradient(135deg, #ff4d4f, #ff7a45);
    color: white;
    font-size: 22rpx;
    padding: 8rpx 20rpx;
    border-radius: 20rpx;
    z-index: 2;
  }
}

.product-card {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  
  &.featured {
    border: 2rpx solid #4a90e2;
    box-shadow: 0 6rpx 24rpx rgba(74, 144, 226, 0.15);
  }
  
  .product-header {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;
    position: relative;
    
    .product-badge {
      position: absolute;
      top: -10rpx;
      left: 0;
      color: white;
      font-size: 20rpx;
      padding: 6rpx 16rpx;
      border-radius: 12rpx;
    }
    
    .product-logo {
      width: 80rpx;
      height: 80rpx;
      border-radius: 16rpx;
      margin-right: 20rpx;
    }
    
    .product-info {
      flex: 1;
      
      .product-name {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .product-company {
        display: block;
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .match-rate {
      font-size: 28rpx;
      font-weight: bold;
      color: #4a90e2;
    }
  }
  
  .product-features {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 24rpx;
    
    .feature-tag {
      background: #f0f7ff;
      color: #4a90e2;
      font-size: 22rpx;
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      margin-right: 16rpx;
      margin-bottom: 12rpx;
    }
  }
  
  .product-details {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 24rpx;
    
    .detail-item {
      width: 48%;
      margin-bottom: 20rpx;
      
      .detail-label {
        display: block;
        font-size: 24rpx;
        color: #999;
        margin-bottom: 8rpx;
      }
      
      .detail-value {
        display: block;
        font-size: 26rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .product-summary {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24rpx;
    background: #f8fafc;
    border-radius: 12rpx;
    padding: 20rpx;
    
    .summary-item {
      text-align: center;
      flex: 1;
      
      .summary-label {
        display: block;
        font-size: 22rpx;
        color: #999;
        margin-bottom: 8rpx;
      }
      
      .summary-value {
        display: block;
        font-size: 26rpx;
        color: #333;
        font-weight: 500;
      }
    }
  }
  
  .product-match-reasons {
    background: #f6ffed;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 24rpx;
    
    .match-reason-title {
      display: block;
      font-size: 24rpx;
      color: #52c41a;
      font-weight: bold;
      margin-bottom: 12rpx;
    }
    
    .match-reasons {
      .match-reason {
        display: block;
        font-size: 24rpx;
        color: #666;
        line-height: 1.5;
        margin-bottom: 8rpx;
        
        &:before {
          content: "• ";
          color: #52c41a;
        }
      }
    }
  }
  
  .product-actions {
    display: flex;
    
    .detail-btn {
      flex: 1;
      background: white;
      color: #4a90e2;
      border: 1rpx solid #4a90e2;
      border-radius: 50rpx;
      padding: 20rpx;
      font-size: 26rpx;
      margin-right: 20rpx;
    }
    
    .apply-btn {
      flex: 1;
      background: linear-gradient(135deg, #4a90e2, #5aa0f0);
      color: white;
      border-radius: 50rpx;
      padding: 20rpx;
      font-size: 26rpx;
      font-weight: bold;
      box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.3);
    }
  }
}

.other-products {
  .section-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 24rpx;
  }
}

.empty-state {
  text-align: center;
  padding: 80rpx 0;
  
  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 40rpx;
    opacity: 0.6;
  }
  
  .empty-title {
    display: block;
    font-size: 32rpx;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .empty-desc {
    display: block;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 40rpx;
    line-height: 1.5;
  }
  
  .empty-actions {
    display: flex;
    justify-content: center;
    
    .reset-btn {
      background: white;
      color: #4a90e2;
      border: 1rpx solid #4a90e2;
      border-radius: 50rpx;
      padding: 20rpx 40rpx;
      font-size: 26rpx;
      margin-right: 20rpx;
    }
    
    .contact-btn {
      background: linear-gradient(135deg, #4a90e2, #5aa0f0);
      color: white;
      border-radius: 50rpx;
      padding: 20rpx 40rpx;
      font-size: 26rpx;
    }
  }
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
  
  .match-btn {
    background: linear-gradient(135deg, #4a90e2, #5aa0f0);
    color: white;
    border-radius: 50rpx;
    padding: 24rpx;
    font-size: 30rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.3);
    
    &:disabled {
      background: #ccc;
      box-shadow: none;
    }
    
    .btn-text {
      color: white;
      margin-right: 12rpx;
    }
    
    .btn-count {
      background: rgba(255, 255, 255, 0.3);
      color: white;
      font-size: 22rpx;
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
    }
  }
}
</style>